<?php
namespace App\Http\Controllers\Api\V1;

use App\Models\Order;
use App\Models\Product;
use App\Models\UserApplyCash;
use App\Models\UserProduct;
use App\TraitHelper\RequestHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

/**
 * Created by PhpStorm.
 * User: xinghuo
 * Date: 2017/7/11
 * Time: 上午12:53
 */
class MyController
{
    use RequestHelper;

    public function product(Request $request)
    {
        $user = $this->getLoginUserInfo($request);

        $data['product'] = [];
        $products = UserProduct::whereUserId($user['id'])->orderBy('id', 'desc')->get();
        if ($products) {
            foreach ($products as $map) {
                if ($map->order && $map->product) {
                    $item = [
                        'device_id' => $map->id,
                        'title' => '安装地址:' . $map->order->address . ' ' . $map->order->street,
                        'buy_time' => $map->order->pay_time ? $map->order->pay_time : '',
                        'status' => $map->status?$map->status:0,
                        'statusText' => $map->status == 1 ? '已安装' : '未安装',
                        'image' => url($map->product->image[0]) ?: Product::$default_image,
                    ];
                    $data['product'][] = $item;
                };
            }
        }
        return $this->formatJson(true, $data);
    }

    public function share(Request $request)
    {
        $user = $this->getLoginUserInfo($request);
        $orders = Order::whereParentUserId($user['id'])->where('pay_time', '>', '0')->get();

        $total = $apply = $unapply = 0;
        if ($orders) {
            foreach ($orders as $order) {
                $data['product'][] = [
                    'title' => '安装地址:' . $order->address . ' ' . $order->street,
                    'buy_time' => $order->pay_time,
                    'appleyStatusText' => $order->apply_status == 1 ? '已提现' : '未体现',
                    'applyStatus' => $order->apply_status,
                    'number' => '',
                    'image' => isset($order->product->image) ? url($order->product->image[0]) : Product::$default_image,
                    'order_id' => $order->id,
                ];
                if ($order->apply_status) {
                    $apply += $order->commission;
                }else{
                    $unapply += $order->commission;
                }
                $total += $order->commission;
            }
        }
        $data['total'] = $total;
        $data['apply'] = $apply;
        $data['unapply'] = $unapply;
        return $this->formatJson(true, $data);
    }

    public function apply(Request $request)
    {
        $user = $this->getLoginUserInfo($request);

        $validator = \Validator::make($request->all(), [
            'alipay' => 'required',
            'order_id_list' => 'required',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return $this->formatJson(false, [], $messages->first());
        }
        $order_list = $request->input('order_id_list');
        $price = Order::getApplyMoney($user, $order_list);
        $orders = Order::whereParentUserId($user['id'])->whereIn('id', explode(',', $order_list))->get();
        try {
            \DB::beginTransaction();
            foreach ($orders as $order) {
                $order->apply_status = Order::APPLY_STATUS_WAITING;
                $order->save();
            }
            UserApplyCash::create([
                'alipay' => $request->input('alipay'),
                'price' => $price,
                'user_id' => $user['id'],
                'order_id_list' => $order_list
            ]);
            \DB::commit();
            return $this->formatJson(true, [], "申请已提交!等待处理.");

        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->formatJson(false, [], $e->getMessage());
        }

    }

    public function productDetail(Request $request)
    {
        $user = $this->getLoginUserInfo($request);
        $validator = \Validator::make($request->all(), [
            'device_id' => 'required',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return $this->formatJson(false, [], $messages->first());
        }
        $device_id = $request->input('device_id');
        $user = UserProduct::whereUserId($user['id'])->find($device_id);
        if (!$user || !$user->order || !$user->product) {
            return $this->formatJson(false, [], "设备信息不存在!");
        }
        /**
         * @var order Order
         */
        $order = $user->order;
        $data['order_id'] = $order->sn;
        $data['order']['price'] = $order->price;
        $data['order']['create_at'] = $order->pay_time;
        $product = Product::find($user->product_id);
        $images = $product->images;
        $data['product'] = [
            'title' => $user->product->title,
            'buy_time' => $order->pay_time ? $order->pay_time : '',
            'statusText' => $user->status == UserProduct::STATUS_INSTALL ? "已安装" : "未安装",
            'status' => $user->status,
            'images' => isset($images[0]) ? url($images[0]) :
                'http://upload.cheaa.com/2016/0504/1462325326710.png'
            ,
        ];
        $data['address'] = [
            'username' => $order->username,
            'mobile' => $order->mobile,
            'payTypeTip' => $order->pay_type == Order::PAY_TYPE_ALIPAY ? '支付宝' : "微信",
            'payType' => $order->pay_type,
        ];
        if ($user->installed_at && $user->status ==  UserProduct::STATUS_INSTALL ) {
            $day = (time() - strtotime($user->installed_at)) / 86400;
            $data['deveice_info'] = [
                'use_day' => intval($day),
                'last_change_time' => '' . $user->last_change_time,
                'next_change_time' => '' . $user->next_change_time,
                'continue_time' => '' . $user->continue_time,
                'end_time' => '' . $user->end_time,
            ];
            $data['change_filter_time'] = [
            ];
            if ($user->eventFilter) {
                foreach ($user->eventFilter as $filter) {
                    $data['change_filter_time'][] = ["date" => '' . $filter->created_at, 'title' => $filter->title];
                }

            }

            $data['other_time'] = [
            ];
            if ($user->eventFix) {
                foreach ($user->eventFix as $filter) {
                    $data['other_time'][] = ["date" => '' . $filter->created_at, 'title' => $filter->title];
                }

            }
        }
        return $this->formatJson(true, $data);

    }
}